use std::{env, fs};
use serde_yaml::from_str;
use crate::extends::core::config::app_context::{AppContext, TempApplicationContext, TempFrameworkContext};

#[derive(Debug)]
pub struct AppCtxHandler;

impl AppCtxHandler {
    // 从文件系统动态加载配置的函数
    pub fn load_config() -> AppContext {
        // 读取基础配置文件 application.yml
        let mut app_ctx_config = AppContext::default();
        let current_dir = env::current_dir().expect("Failed to get current directory");

        let base_config_path = current_dir.join("src/application.yml");
        let base_config_str = fs::read_to_string(&base_config_path)
            .expect(&format!("Failed to read {:?}", base_config_path));
        let temp_app_ctx_config: TempApplicationContext = from_str(&base_config_str)
            .expect("Failed to parse application.yml!");
        app_ctx_config.application = temp_app_ctx_config.application;

        // 获取活动配置文件的名称
        let active_profile = &app_ctx_config.application.profiles.active;
        let profile_yaml_filename = format!("src/application-{}.yml", active_profile);
        let profile_config_path = current_dir.join(&profile_yaml_filename);
        // 读取环境配置文件
        let profile_config_str = fs::read_to_string(&profile_config_path)
            .expect(&format!("Failed to read {:?}", profile_config_path));
        let framework_config: TempFrameworkContext = from_str(&profile_config_str)
            .expect(&format!("Failed to parse {:?}", profile_config_path));

        // 合并配置
        app_ctx_config.framework = framework_config.framework;
        app_ctx_config.microservices = framework_config.microservices;

        app_ctx_config
    }
}